import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { translateText } from '../utils/autoTranslate'

interface AutoTranslateProps {
  text: string
  className?: string
  // 当 target 语言与文本语言一致时是否强制翻译
  force?: boolean
}

export default function AutoTranslate({ text, className, force = false }: AutoTranslateProps) {
  const { i18n } = useTranslation()
  const [display, setDisplay] = useState(text)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    let mounted = true
    async function run() {
      setLoading(true)
      try {
        const target = (i18n.language === 'en' ? 'en' : 'zh') as 'en' | 'zh'
        const result = await translateText(text, target)
        if (!mounted) return
        // 若不强制翻译且翻译结果等于原文，则保持原文
        setDisplay(force ? result : (result || text))
      } catch (e) {
        if (!mounted) return
        setDisplay(text)
      } finally {
        if (!mounted) return
        setLoading(false)
      }
    }
    run()
    return () => { mounted = false }
    // 语言或文本变化时重新翻译
  }, [text, i18n.language])

  return (
    <span className={className}>
      {loading ? text : display}
    </span>
  )
}